package org.realogic.cfm.common.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class OrderedMap<K,V> extends HashMap<K,V> {

	private static final long serialVersionUID = -7798831702306498755L;
	
	private List<K> orderedKeys = new LinkedList<K>();

	public Set<K> keySet() {
		return new OrderedSet<K>(orderedKeys);
	}

	public V put(K key, V value) {
		if (!orderedKeys.contains(key)) {
			orderedKeys.add(key);
		}
		return super.put(key, value);
	}

	public void clear() {
		super.clear();
		orderedKeys.clear();
	}

	public V remove(Object key) {
		if (orderedKeys.contains(key)) {
			orderedKeys.remove(key);
		}
		return super.remove(key);
	}

	public Collection<V> values() {
		Iterator<K> i = orderedKeys.iterator();
		if (!i.hasNext()) {
			return null;
		}

		List<V> values = new ArrayList<V>();
		while (i.hasNext()) {
			values.add(this.get(i.next()));
		}
		return values;
	}
}
